package com.lzxuni.modules.pestdetails.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.utils.FileUtil;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.UuidUtil;
import com.lzxuni.common.utils.date.DateUtil;
import com.lzxuni.modules.basics.entity.BasicTree;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.FileEntity;
import com.lzxuni.modules.common.entity.PageData;
import com.lzxuni.modules.common.entity.PageParameter;
import com.lzxuni.modules.common.service.FileEntityService;
import com.lzxuni.modules.pestdetails.entity.Pest;
import com.lzxuni.modules.pestdetails.entity.PestDetails;
import com.lzxuni.modules.pestdetails.service.PestDetailsService;
import com.lzxuni.modules.pestdetails.service.PestService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 虫情 前端控制器
 * </p>
 *
 * @author rdf
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/LR_PestManagement/PestManagement")
public class PestController extends BaseController{

    @Autowired
    private PestService pestService;
    @Autowired
    private FileEntityService fileEntityService;
    @Autowired
    private PestDetailsService pestDetailsService;
    private static String typeName = "虫情管理上传图片";
    private static String ywType = "pestdisgl_img";

    //主页面
    @RequestMapping("/Index")
    public ModelAndView Index() {
        ModelAndView mv = new ModelAndView("/LR_Pest/pestmanagement/index");
        return mv;
    }
    //查询数据
    @RequestMapping("/GetList")
    public Object GetList(String pagination,String queryJson){
        PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
        Pest pest = JSON.parseObject(queryJson, Pest.class);
        PageData pageData = getPageData(pestService.queryPage(pageParameter, pest));
        return R.ok().put("data", pageData);
    }
    //双击查看
    @RequestMapping("/QueryImg")
    public ModelAndView QueryImg(String keyValue) throws Exception {
        ModelAndView mv = new ModelAndView("/LR_Pest/pestmanagement/img");
        FileEntity fileBeanCustom = new FileEntity();
        fileBeanCustom.setYwId(keyValue);
        List<FileEntity> fileEntities = fileEntityService.queryListByFileEntity(fileBeanCustom);
        mv.addObject("fileEntities", fileEntities);
        return mv;
    }

    //表单页
    @RequestMapping("/Form")
    public ModelAndView Form(String keyValue,String queryJson,String type) throws Exception{
        ModelAndView mv = new ModelAndView("/LR_Pest/pestmanagement/form");
        BasicTree basicTree = JSON.parseObject(queryJson, BasicTree.class);
        mv.addObject("basicTree", basicTree);
        FileEntity fileBeanCustom = new FileEntity();
        fileBeanCustom.setYwId(keyValue);
        fileBeanCustom.setYwType(ywType);
        mv.addObject("imgCount", fileEntityService.queryNumByFileEntity(fileBeanCustom));
        mv.addObject("id", keyValue);
        Pest pestShuju = pestService.getById(keyValue);
        List<PestDetails> pestDetaList = pestDetailsService.list(new QueryWrapper<PestDetails>().eq("pest_id", keyValue).orderByAsc("create_date"));
        if(pestDetaList.size()>0){
            mv.addObject("type", "edit");
            mv.addObject("pestDetaList", pestDetaList);
            mv.addObject("detailCoount",pestDetaList.size());
        }else{
            mv.addObject("type", "add");
        }
//        List<FileEntity> fileEntities = fileEntityService.queryListByFileEntity(fileBeanCustom);
//        mv.addObject("fileEntities", fileEntities);

//        mv.addObject("pestShuju", pestShuju);
//        mv.addObject("type", type);
        return mv;
    }
    @RequestMapping("/SaveForm")
    public Object insertDo(String keyValue,Pest pest,String parentId,PestDetails pestDetails, String subJson,String pestdisgl_imgs,String queryJson) throws Exception{
        List<PestDetails> pestDetailList= JSON.parseArray(subJson, PestDetails.class);
        if(StringUtils.isEmpty(keyValue)){
            String ywId = UuidUtil.get32UUID();
            if (!com.lzxuni.common.utils.StringUtils.isEmpty(pestdisgl_imgs) && !"&amp;nbsp;".equals(pestdisgl_imgs)) {
                fileEntityService.insert(pestdisgl_imgs.replace("&quot;", "\""), ywId, typeName, ywType, null);
            }
            int temp = 0;
            for(PestDetails pestDetails1 :pestDetailList ){
                pestDetails1.setPestId(ywId);
                if(pestDetails1.getStatusFs().equals("1")){
                    temp++;
                }
            }
            if(temp > 0){
                pest.setIsred(1);//预警表示
            }else{
                pest.setIsred(0);
            }
            pest.setIsedit(0);
            pest.setPestId(ywId);
            pest.setLandId(parentId);
            pest.setCreateTime(pest.getCreateTime());
            pestService.save(pest);
            pestDetailsService.saveBatch(pestDetailList);
            return R.ok("保存成功");
        }else{
            fileEntityService.deleteByYwId(keyValue);
            if (!StringUtils.isEmpty(pestdisgl_imgs) && !"&amp;nbsp;".equals(pestdisgl_imgs)) {
                fileEntityService.insert(pestdisgl_imgs.replace("&quot;", "\""), keyValue, typeName, ywType, null);
            }
            pestDetailsService.remove(new QueryWrapper<PestDetails>().eq("pest_id",keyValue));
            int temp = 0;
            for(PestDetails pestDetails1 :pestDetailList ){
                pestDetails1.setPestId(keyValue);
                if(pestDetails1.getStatusFs().equals("1")){
                    temp++;
                }
            }
//            pest = pestService.getById(keyValue);
            pest.setPestId(keyValue);
            pest.setIsedit(1);//编辑表示
            pest.setCreateTime(pest.getCreateTime());
            if(temp > 0){
                pest.setIsred(1);//预警表示
            }else{
                pest.setIsred(0);
            }
            pestService.updateById(pest);
            pestDetailsService.saveBatch(pestDetailList);
            return R.ok("修改成功");
        }
    }
    //删除数据
    @RequestMapping("/DeleteForm")
    public Object delete(String keyValue) {
        pestService.removeById(keyValue);
        fileEntityService.deleteByYwId(keyValue);
        pestDetailsService.remove(new QueryWrapper<PestDetails>().eq("pest_id",keyValue));
        return R.ok("删除成功");
    }

    //导出
    @RequestMapping("/Export")
    public void exportExcel(HttpServletResponse response, String queryJson, HttpServletRequest request) throws IOException {
        Pest pest = JSON.parseObject(queryJson, Pest.class);
        //System.out.println(diseaseManagement.toString());
        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "虫情管理" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = pestService.exportExcel(pest);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }

    //查看详情
    @RequestMapping("/IndexXq")
    public ModelAndView See(String keyValue) throws Exception{
        ModelAndView mv = new ModelAndView("/LR_Pest/pestmanagement/index_details");
        mv.addObject("keyValue", keyValue) ;
        return mv;
    }
    //查询详情数据
    @RequestMapping("/GetListXq")
    public Object GetListXq(String keyValue,String pagination,String queryJson){
        PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
        Pest pest = JSON.parseObject(queryJson, Pest.class);
//        Pest pest = new Pest();
        pest.setPestId(keyValue);
        PageData pageData = getPageData(pestService.queryPagexq(pageParameter, pest));
        return R.ok().put("data", pageData) ;
    }

    //导出
    @RequestMapping("/ExportXq")
    public void ExportXq(HttpServletResponse response, Pest pest, HttpServletRequest request) throws IOException {
//        Pest pest = JSON.parseObject(queryJson, Pest.class);
        //System.out.println(diseaseManagement.toString());
        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "虫情详情" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = pestService.exportExcelXq(pest);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }

    //查询预警信息(主页面使用)
    @RequestMapping("/QueryKCunLiang")
    public Object queryyuliang() {
        List<Pest> list = pestService.queryYuJing();
        return list;
    }

}

